package org.myy.learn.hot.堆;

public class 数组中的第K个最大元素 {
    public int findKthLargest(int[] nums, int k) {
        int heapSize = nums.length;
        buildMaxHeap(nums, heapSize);                                       //构建最大堆
        for (int i = nums.length - 1; i >= nums.length - k + 1; --i) {      //nums.length - k + 1，实际是遍历k - 1次
            swap(nums, 0, i);                                             //堆顶 <>  尾节点
            --heapSize;
            maxHeapify(nums, 0, heapSize);                                //重构最大堆
        }
        return nums[0];
    }

    public void buildMaxHeap(int[] a, int heapSize) {
        for (int i = heapSize / 2 - 1; i >= 0; --i) {                       // heapSize / 2 - 1   [最后]根节点下标
            maxHeapify(a, i, heapSize);
        }
    }

    public void maxHeapify(int[] a, int i, int heapSize) {
        int l = i * 2 + 1, r = i * 2 + 2, largest = i;                       // i * 2 + 1   [最后]根节点的左下标     i * 2 + 2    [最后]根节点的右下标
        if (l < heapSize && a[l] > a[largest]) {largest = l;}
        if (r < heapSize && a[r] > a[largest]) {largest = r;}                //l < heapSize  判断是否超出
        if (largest != i) {
            swap(a, i, largest);                                             //交换
            maxHeapify(a, largest, heapSize);                                //递归 子树
        }
    }

    public void swap(int[] a, int i, int j) {
        int temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }
}
